<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>病人中心</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .prescription-list { list-style-type: none; padding-left: 0; }
        .prescription-list li { background-color: #f8f9fa; border: 1px solid #dee2e6; margin-bottom: 5px; padding: 5px 10px; border-radius: .25rem; }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-success">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">医院管理系统</a>
            <span class="navbar-text">欢迎, {{ patient.name }}</span>
            <a href="/" class="btn btn-sm btn-outline-light ms-auto">退出登录</a>
        </div>
    </nav>
    <main class="container mt-4">
        <div class="row">
            <!-- 左侧：个人信息和挂号 -->
            <div class="col-md-4">
                <div class="card mb-4">
                    <div class="card-header"><h4>个人信息</h4></div>
                    <div class="card-body">
                        <p><strong>病历号:</strong> {{ patient.id }}</p>
                        <p><strong>姓名:</strong> {{ patient.name }}</p>
                        <p><strong>性别:</strong> {{ '男' if patient.gender == 'M' else '女' }}</p>
                        <p><strong>电话:</strong> {{ patient.phone_number }}</p>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header"><h4>在线挂号</h4></div>
                    <div class="card-body">
                        <form id="appointmentForm">
                            <div class="mb-3">
                                <label for="departmentSelect" class="form-label">选择科室</label>
                                <select id="departmentSelect" class="form-select"></select>
                            </div>
                            <div class="mb-3">
                                <label for="doctorSelect" class="form-label">选择医生</label>
                                <select id="doctorSelect" class="form-select" required></select>
                            </div>
                            <button type="submit" class="btn btn-primary w-100">确认挂号</button>
                        </form>
                    </div>
                </div>
            </div>

            <!-- 右侧：我的预约记录 -->
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header"><h4>我的就诊记录</h4></div>
                    <div class="card-body">
                        <div id="appointmentAccordion">
                            <!-- JS动态填充Accordion -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const PATIENT_ID = "{{ patient.id }}";
        let allDoctors = []; // 用于存储所有医生信息

        document.addEventListener('DOMContentLoaded', () => {
            loadInitialData(); // 加载医生和科室数据
            loadPatientAppointments(); // 加载病人自己的预约

            // 绑定事件
            document.getElementById('departmentSelect').addEventListener('change', filterDoctors);
            document.getElementById('appointmentForm').addEventListener('submit', handleCreateAppointment);
        });

        // 页面加载时获取所有基础数据
        async function loadInitialData() {
            try {
                // 获取所有医生
                const docResponse = await fetch('/api/doctors/');
                const doctors = await docResponse.json();
                allDoctors = doctors; // 确保allDoctors被赋值
                console.log("Fetched Doctors:", allDoctors); // 新增日志

                // 获取所有科室
                const deptResponse = await fetch('/api/departments/');
                const departments = await deptResponse.json();
                console.log("Fetched Departments:", departments); // 新增日志

                const deptSelect = document.getElementById('departmentSelect');
                deptSelect.innerHTML = '<option value="">所有科室</option>' + departments.map(d => `<option value="${d.id}">${d.name}</option>`).join('');

                filterDoctors(); // 初始显示所有医生
            } catch (error) {
                console.error("加载基础数据失败:", error);
            }
        }

        // 根据选择的科室筛选医生
        function filterDoctors() {
            const deptId = document.getElementById('departmentSelect').value;
            const docSelect = document.getElementById('doctorSelect');

            const filtered = deptId ? allDoctors.filter(d => d.department.id == deptId) : allDoctors;

            docSelect.innerHTML = filtered.map(d => `<option value="${d.id}">${d.name} (${d.department.name})</option>`).join('');
        }

        // 提交挂号请求
        async function handleCreateAppointment(e) {
            e.preventDefault();
            const doctorId = document.getElementById('doctorSelect').value;
            if (!doctorId) {
                alert('请选择一位医生！');
                return;
            }

            const data = {
                patient_id: PATIENT_ID,
                doctor_id: doctorId
            };

            const response = await fetch('/api/appointments/', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(data)
            });

            if (response.ok) {
                alert('挂号成功！');
                loadPatientAppointments(); // 刷新记录
            } else {
                alert('挂号失败，请重试。');
            }
        }

        // 加载病人的预约记录
        async function loadPatientAppointments() {
            const response = await fetch(`/api/appointments/patient/${PATIENT_ID}`);
            const appointments = await response.json();

            const accordion = document.getElementById('appointmentAccordion');
            if (appointments.length === 0) {
                accordion.innerHTML = '<p class="text-center text-muted">暂无就诊记录</p>';
                return;
            }

            accordion.innerHTML = appointments.map((appt, index) => `
                <div class="accordion-item">
                    <h2 class="accordion-header">
                        <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapse${appt.id}">
                            <strong>${appt.appointment_date}</strong> - ${appt.doctor.department.name} - ${appt.doctor.name} 医生
                            <span class="badge ${appt.status === '已就诊' ? 'bg-success' : 'bg-warning'} ms-auto me-2">${appt.status}</span>
                        </button>
                    </h2>
                    <div id="collapse${appt.id}" class="accordion-collapse collapse" data-bs-parent="#appointmentAccordion">
                        <div class="accordion-body">
                            <h6>处方详情:</h6>
                            <ul class="prescription-list">
                                ${appt.prescriptions.length > 0
                                    ? appt.prescriptions.map(p => `<li><strong>${p.item_name}:</strong> ${p.details}</li>`).join('')
                                    : '<li>暂无处方信息</li>'
                                }
                            </ul>
                        </div>
                    </div>
                </div>
            `).join('');
        }
    </script>
</body>
</html>